package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    public static int maxSize=100;
    public static int maxuser=0;
    public static String[] logined = new String[maxSize];

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/wallpaper";
    static final String USER = "root";
    static final String PASS = "88888888";

    GreetingController(){
        for(int i = 0; i < maxSize; ++i){
            logined[i]=new String("");
        }
    }

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(value = "/auth")
    public String auth(@RequestParam(value="name", defaultValue="World") String name,
                       @RequestParam(value="passwd", defaultValue="World") String passwd) {

        // 注册 JDBC 驱动
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            Statement stmt = null;
            conn = DriverManager.getConnection(DB_URL,USER,PASS);

            stmt = conn.createStatement();
            String sql;
            sql = "SELECT passwd FROM users WHERE name=\"%s\"";
            ResultSet rs = stmt.executeQuery(String.format(sql, name));
            if(rs.next()){
                if(rs.getString("passwd").equals(passwd))
                {
                    //add token and return success
                    logined[maxuser] = name;
                    maxuser++;
                    return "success";
                }
                else{
                    return "invalid password";
                }
            }
            else{
                return "no such user";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Success";
        //return "Fail";
    }
}
